package com.atjava.webspider.gui.site;

import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.apache.commons.lang.StringUtils;

import com.atjava.webspider.gui.output.NewVarGui;
import com.atjava.webspider.gui.page.NewPageGui;
import com.atjava.webspider.gui.table.DefaultTable;
import com.atjava.webspider.gui.table.DefaultTableModel;
import com.atjava.webspider.logic.CommonLogic;
import com.atjava.webspider.logic.ConfigLogic;
import com.atjava.webspider.model.Page;
import com.atjava.webspider.model.Replace;
import com.atjava.webspider.model.Site;
import com.atjava.webspider.model.SiteConfig;
import com.atjava.webspider.services.TableService;
import com.atjava.webspider.util.DialogUtil;
import com.atjava.webspider.util.TableUtil;

public class NewSiteGui extends JDialog {

	private static final long serialVersionUID = 1L;
	private static final int REP_TABLE_ROWS = 5;
	private JPanel jContentPane = null;
	
	private JTabbedPane jTabbedPaneMain = null;
	private JPanel jPanelBasic = null;
	private JPanel jPanelOutput = null;
	
	private JLabel jLabel = null;
	private JTextField jTextFieldTskName = null;
	private JPanel jPanelPage = null;
	private JPanel jPanelVar = null;
	private JScrollPane jScrollPanePage = null;
	private JTable jTablePage = null;
	private JScrollPane jScrollPaneVar = null;
	private JTable jTableVar = null;
	private JButton jButtonVar = null;
	private JButton jButtonOutput = null;
	private JButton jButtonOutputDel = null;
	private JButton jButtonDone = null;
	private JLabel jLabel6 = null;
	private JTextField jTextFieldTskCharset = null;
	//private JButton jButtonDelResource = null;
	private Site site;
	private int outputIndex = -1;
	private DefaultTableModel outputModel;
	private DefaultTableModel varModel;
	private JButton jButtonVarDel = null;
	private JButton jButtonOutputView = null;
	private JButton jButtonVarView = null;
	private JPanel jPanelReplace = null;
	private JScrollPane jScrollPaneReplace = null;
	private JTable jTableReplace = null;
	private DefaultTableModel replaceModel = null;
	/**
	 * @param owner
	 */
	public NewSiteGui(Frame owner,boolean modal) {
		this(owner,modal,new Site());
	}
	
	public NewSiteGui(Dialog owner,boolean modal) {
		this(owner,modal,new Site());
	}
	
	public NewSiteGui(Dialog owner,boolean modal,Site site) {
		super(owner,modal);
		this.site = site;
		initialize();
		setTextValue();
	}
	
	public NewSiteGui(Frame owner,boolean modal,Site site) {
		super(owner,modal);
		this.site = site;
		initialize();
		setTextValue();
	}
	
	private void setTextValue(){
		if(site == null)
			return ;
		try {
			if(StringUtils.isNotBlank(site.getCharset()))
				jTextFieldTskCharset.setText(site.getCharset());
			
			if(StringUtils.isNotBlank(site.getName())){
				jTextFieldTskName.setText(site.getName());
				jTextFieldTskName.setEnabled(false);
			}
			
			if(site.getPages() != null){
				DefaultTableModel dtm = (DefaultTableModel)jTablePage.getModel();
				TableService serv = TableService.getInstance();
				dtm.updateAllData(serv.getPageTable(site.getPages()));
				if(dtm.getRowCount() > 0)
					jTablePage.setRowSelectionInterval(0, 0);
			}
			if(site.getReplaces() != null){
				DefaultTableModel dtm = (DefaultTableModel)jTableReplace.getModel();
				TableService serv = TableService.getInstance();
				for (int i = 0; i < REP_TABLE_ROWS; i++) {
					if(i < site.getReplaces().size())
						dtm.updateData(i,serv.getReplaceRow(site.getReplaces().get(i)));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			DialogUtil.showError(this, "站点任务失败！");
		}
	}
	
	public DefaultTableModel getOutputModel(){
		return this.outputModel;
	}
	
	public DefaultTableModel getVarModel(){
		return this.varModel;
	}

	public Site getSite(){
		return site;
	}
	
	public int getOutputIndex(){
		return this.outputIndex;
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(605, 456);
		this.setResizable(false);
		this.setTitle("新建站点");
		this.setContentPane(getJContentPane());
		this.setLocationRelativeTo(getOwner());
		this.setModal(true);
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.add(getJTabbedPaneMain(), null);
			jContentPane.add(getJButtonDone(), null);
		}
		return jContentPane;
	}

	/**
	 * This method initializes jTabbedPaneMain	
	 * 	
	 * @return javax.swing.JTabbedPane	
	 */
	private JTabbedPane getJTabbedPaneMain() {
		if (jTabbedPaneMain == null) {
			jTabbedPaneMain = new JTabbedPane();
			jTabbedPaneMain.setBounds(new Rectangle(0, 0, 600, 395));
			jTabbedPaneMain.addTab("基本信息", null, getJPanelBasic(), null);
			jTabbedPaneMain.addTab("页　　面", null, getJPanelOutput(), null);
		}
		return jTabbedPaneMain;
	}

	/**
	 * This method initializes jPanelBasic	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanelBasic() {
		if (jPanelBasic == null) {
			jLabel6 = new JLabel();
			jLabel6.setText("字 符 集：");
			jLabel6.setBounds(new Rectangle(435, 5, 65, 25));
			jPanelBasic = new JPanel();
			jPanelBasic.setLayout(null);
			jLabel = new JLabel();
			jLabel.setText("站点名称：");
			jLabel.setSize(new Dimension(65, 25));
			jLabel.setLocation(new Point(5, 5));
			jPanelBasic.add(getJTextFieldTskName(), null);
			jPanelBasic.add(jLabel, null);
			jPanelBasic.add(getJPanelReplace(), null);
			jPanelBasic.add(jLabel6, null);
			jPanelBasic.add(getJTextFieldTskCharset(), null);
		}
		return jPanelBasic;
	}

	/**
	 * This method initializes jPanelOutput	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanelOutput() {
		if (jPanelOutput == null) {
			jPanelOutput = new JPanel();
			jPanelOutput.setLayout(null);
			jPanelOutput.add(getJPanelPage(), null);
			jPanelOutput.add(getJPanelVar(), null);
		}
		return jPanelOutput;
	}

	/**
	 * This method initializes jTextFieldTskName	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextFieldTskName() {
		if (jTextFieldTskName == null) {
			jTextFieldTskName = new JTextField();
			jTextFieldTskName.setBounds(new Rectangle(75, 5, 330, 25));
			jTextFieldTskName.setForeground(Color.black);
		}
		return jTextFieldTskName;
	}

	/**
	 * This method initializes jPanelPage	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanelPage() {
		if (jPanelPage == null) {
			jPanelPage = new JPanel();
			jPanelPage.setLayout(null);
			jPanelPage.setBounds(new Rectangle(1, 2, 592, 180));
			jPanelPage.setBorder(BorderFactory.createTitledBorder(null, " 页面列表 "));
			jPanelPage.add(getJScrollPanePage(), null);
			jPanelPage.add(getJButtonOutput(), null);
			jPanelPage.add(getJButtonOutputDel(), null);
			jPanelPage.add(getJButtonOutputView(), null);
		}
		return jPanelPage;
	}

	/**
	 * This method initializes jPanelVar	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanelVar() {
		if (jPanelVar == null) {
			jPanelVar = new JPanel();
			jPanelVar.setLayout(null);
			jPanelVar.setBounds(new Rectangle(1, 187, 592, 180));
			jPanelVar.setBorder(BorderFactory.createTitledBorder(null, " \u53d8\u91cf\u5217\u8868 "));
			jPanelVar.add(getJScrollPaneVar(), null);
			jPanelVar.add(getJButtonVar(), null);
			jPanelVar.add(getJButtonVarDel(), null);
			jPanelVar.add(getJButtonVarView(), null);
		}
		return jPanelVar;
	}

	/**
	 * This method initializes jScrollPanePage	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPanePage() {
		if (jScrollPanePage == null) {
			jScrollPanePage = new JScrollPane();
			jScrollPanePage.setBounds(new Rectangle(8, 20, 576, 121));
			jScrollPanePage.setViewportView(getJTablePage());
		}
		return jScrollPanePage;
	}

	/**
	 * This method initializes jTablePage	
	 * 	
	 * @return javax.swing.JTable	
	 */
	public JTable getJTablePage() {
		if (jTablePage == null) {
			String [] colums = {"页面名称","页面级别","变量个数"};
			outputModel = new DefaultTableModel(colums);
			jTablePage = new DefaultTable(outputModel);
			jTablePage.setRequestFocusEnabled(false);
			//调整大小
			TableUtil.fitTableColumns(jTablePage,new int[]{150,40,40});
			jTablePage.setRowHeight(25);
			TableUtil.setTableAlign(jTablePage, JLabel.CENTER);
			jTablePage.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			jTablePage.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
				public void valueChanged(ListSelectionEvent evt) {
					int index = jTablePage.getSelectedRow();
					if((index >= 0 && (index != outputIndex || outputIndex == -1))){
						try {
							outputIndex = index;
							Page page = site.getPages().get(index);
							TableService tabService = TableService.getInstance();
							List<String []> vars = tabService.getVarTable(page.getVariables());
							varModel.updateAllData(vars);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			});
		}
		return jTablePage;
	}

	/**
	 * This method initializes jScrollPaneVar	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPaneVar() {
		if (jScrollPaneVar == null) {
			jScrollPaneVar = new JScrollPane();
			jScrollPaneVar.setBounds(new Rectangle(8, 20, 576, 121));
			jScrollPaneVar.setViewportView(getJTableVar());
		}
		return jScrollPaneVar;
	}

	/**
	 * This method initializes jTableVar	
	 * 	
	 * @return javax.swing.JTable	
	 */
	private JTable getJTableVar() {
		if (jTableVar == null) {
			String [] colums = {"变量名","取值规则","组号"};
			varModel = new DefaultTableModel(colums);
			jTableVar = new DefaultTable(this.varModel);
			jTableVar.setRowHeight(25);
			jTableVar.setRequestFocusEnabled(false);
			jTableVar.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			TableUtil.setTableAlign(jTableVar, JLabel.CENTER);
			//调整大小
			TableUtil.fitTableColumns(jTableVar,new int[]{15,420,15});
		}
		return jTableVar;
	}

	/**
	 * This method initializes jButtonVar	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonVar() {
		if (jButtonVar == null) {
			jButtonVar = new JButton();
			jButtonVar.setBounds(new Rectangle(297, 147, 90, 25));
			jButtonVar.setText("新建变量");
			jButtonVar.addMouseListener(new MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					int rows = outputModel.getRowCount();
					int n = jTablePage.getSelectedRow();
					if(rows > 0 && n >= 0){
						NewVarGui newVar = new NewVarGui(NewSiteGui.this,true);
						newVar.setVisible(true);
					}else{
						DialogUtil.showWarning(NewSiteGui.this, "请选择一条输出记录！");
					}
				}
			});
		}
		return jButtonVar;
	}

	/**
	 * This method initializes jButtonOutput	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonOutput() {
		if (jButtonOutput == null) {
			jButtonOutput = new JButton();
			jButtonOutput.setBounds(new Rectangle(297, 147, 90, 25));
			jButtonOutput.setText("新建页面");
			jButtonOutput.addMouseListener(new MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					NewPageGui newPage = new NewPageGui(NewSiteGui.this,true);
					newPage.setVisible(true);
				}
			});
		}
		return jButtonOutput;
	}
	
	/**
	 * This method initializes jButtonOutputDel	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonOutputDel() {
		if (jButtonOutputDel == null) {
			jButtonOutputDel = new JButton();
			jButtonOutputDel.setBounds(new Rectangle(495, 147, 90, 25));
			jButtonOutputDel.setText("删除页面");
			jButtonOutputDel.addMouseListener(new MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					int rows = outputModel.getRowCount();
					int n = jTablePage.getSelectedRow();
					if(rows > 0 && n >= 0){
						site.getPages().remove(n);
						outputModel.removeData(n);
						outputIndex = -1;
						varModel.removeAllData();
					}
				}
			});
		}
		return jButtonOutputDel;
	}

	/**
	 * This method initializes jButtonDone	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonDone() {
		if (jButtonDone == null) {
			jButtonDone = new JButton();
			jButtonDone.setText("完成");
			jButtonDone.setBounds(new Rectangle(536, 397, 60, 26));
			jButtonDone.addMouseListener(new MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					if(jTableReplace.getCellEditor() != null)
						jTableReplace.getCellEditor().stopCellEditing();
					
					Site site = NewSiteGui.this.site;
					try {
						//站点基本信息
						site.setCharset(NewSiteGui.this.jTextFieldTskCharset.getText());
						site.setName(NewSiteGui.this.jTextFieldTskName.getText());
						//替换
						site.setReplaces(new ArrayList<Replace>());
						for (int i = 0; i < jTableReplace.getRowCount(); i++) {
							//表达式
							String regexp = (String)jTableReplace.getValueAt(i, 0);
							if(StringUtils.isBlank(regexp))
								continue;
							//组号
							int group = Integer.parseInt((String)jTableReplace.getValueAt(i, 1));
							//替换
							String replacement = (String)jTableReplace.getValueAt(i, 2);
							replacement = replacement == null ? "" : replacement;
							Replace r = new Replace();
							r.setRegexp(regexp);
							r.setGroupNum(group);
							r.setReplacement(replacement);
							site.getReplaces().add(r);
						}
						
						SiteConfig sitecfg = ConfigLogic.getSiteConfig();
						if(sitecfg.getSites() == null)
							sitecfg.setSites(new ArrayList<Site>());
						
						SiteManageGui siteManaeGui = (SiteManageGui)NewSiteGui.this.getOwner();
						int idx = CommonLogic.getIndexByName(sitecfg.getSites(),site.getName());
						TableService tabService = TableService.getInstance();
						//更新
						if(idx >= 0){
							sitecfg.getSites().set(idx, site);
							siteManaeGui.getSiteModel().updateData(idx, tabService.getSiteRow(site));
						//增加
						}else{
							sitecfg.getSites().add(site);
							siteManaeGui.getSiteModel().addData(tabService.getSiteRow(site));
						}
						
						//保存全局信息
						ConfigLogic.saveSiteConfig();
					} catch (Exception ex) {
						ex.printStackTrace();
					}
					NewSiteGui.this.setVisible(false);
				}
			});
			
		}
		return jButtonDone;
	}


	/**
	 * This method initializes jTextFieldTskCharset	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextFieldTskCharset() {
		if (jTextFieldTskCharset == null) {
			jTextFieldTskCharset = new JTextField();
			jTextFieldTskCharset.setBounds(new Rectangle(501, 5, 90, 25));
			jTextFieldTskCharset.setText("gb2312");
		}
		return jTextFieldTskCharset;
	}
	
	/**
	 * This method initializes jButtonDelResource	
	 * 	
	 * @return javax.swing.JButton	
	 
	private JButton getJButtonDelResource() {
		if (jButtonDelResource == null) {
			jButtonDelResource = new JButton();
			jButtonDelResource.setBounds(new Rectangle(474, 326, 90, 25));
			jButtonDelResource.setText("删除资源");
			jButtonDelResource.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED));
			jButtonDelResource.setFont(new Font("Monospaced", Font.PLAIN, 12));
			jButtonDelResource.addMouseListener(new MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					int rows = resourceModel.getRowCount();
					int n = jTableResource.getSelectedRow();
					if(rows > 0 && n >= 0){
						task.getResources().remove(n);
						resourceModel.removeData(n);
					}
				}
			});
		}
		return jButtonDelResource;
	}*/

	/**
	 * This method initializes jButtonVarDel	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonVarDel() {
		if (jButtonVarDel == null) {
			jButtonVarDel = new JButton();
			jButtonVarDel.setBounds(new Rectangle(495, 147, 90, 25));
			jButtonVarDel.setText("删除变量");
			jButtonVarDel.addMouseListener(new MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					int rows = varModel.getRowCount();
					int n = jTableVar.getSelectedRow();
					if(rows > 0 && n >= 0){
						int rows1 = outputModel.getRowCount();
						int n1 = jTablePage.getSelectedRow();
						if(rows1 > 0 && n1 >= 0){
							//所属资源
							Page page = site.getPages().get(outputIndex);
							//删除
							page.getVariables().remove(n);
							varModel.removeData(n);
						}
					}
				}
			});
		}
		return jButtonVarDel;
	}

	/**
	 * This method initializes jButtonOutputView	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonOutputView() {
		if (jButtonOutputView == null) {
			jButtonOutputView = new JButton();
			jButtonOutputView.setBounds(new Rectangle(396, 147, 90, 25));
			jButtonOutputView.setText("查看页面");
			jButtonOutputView.addMouseListener(new MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					int rows = outputModel.getRowCount();
					int n = jTablePage.getSelectedRow();
					if(rows > 0 && n >= 0){
						NewPageGui newPage = new NewPageGui
						(NewSiteGui.this,true,site.getPages().get(n));
						newPage.setVisible(true);
					}
				}
			});
		}
		return jButtonOutputView;
	}

	/**
	 * This method initializes jButtonVarView	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonVarView() {
		if (jButtonVarView == null) {
			jButtonVarView = new JButton();
			jButtonVarView.setBounds(new Rectangle(396, 147, 90, 25));
			jButtonVarView.setText("查看变量");
			jButtonVarView.addMouseListener(new MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					int rows1 = outputModel.getRowCount();
					int n1 = jTablePage.getSelectedRow();
					//获得所选输出
					Page page = site.getPages().get(jTablePage.getSelectedRow());
					if(rows1 > 0 && n1 >= 0){
						int rows = varModel.getRowCount();
						int n = jTableVar.getSelectedRow();
						if(rows > 0 && n >= 0){
							NewVarGui newVar = new NewVarGui
							(NewSiteGui.this,true,page.getVariables().get(n));
							newVar.setVisible(true);
						}
					}
				}
			});
		}
		return jButtonVarView;
	}
	
	/**
	 * This method initializes jTableReplace	
	 * 	
	 * @return javax.swing.JTable	
	 */
	private JTable getJTableReplace() {
		if (jTableReplace == null) {
			String [] columns = new String []{"替换规则","替换组号","替换值"};
			replaceModel = new DefaultTableModel(columns,REP_TABLE_ROWS);
			replaceModel.setEditable(true);
			jTableReplace = new JTable(replaceModel);
			//调整大小
			TableUtil.fitTableColumns(jTableReplace,new int[]{390,50,160});
			jTableReplace.setRowHeight(25);
			TableUtil.setTableAlign(jTableReplace, JLabel.CENTER);
		}
		return jTableReplace;
	}

	/**
	 * This method initializes jPanelReplace	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanelReplace() {
		if (jPanelReplace == null) {
			jPanelReplace = new JPanel();
			jPanelReplace.setLayout(null);
			jPanelReplace.setBounds(new Rectangle(1, 30, 592, 335));
			jPanelReplace.setBorder(BorderFactory.createTitledBorder(null, " 替换规则 "));
			jPanelReplace.add(getJScrollPaneReplace(), null);
		}
		return jPanelReplace;
	}

	/**
	 * This method initializes jScrollPaneReplace	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPaneReplace() {
		if (jScrollPaneReplace == null) {
			jScrollPaneReplace = new JScrollPane();
			jScrollPaneReplace.setBounds(new Rectangle(8, 19, 576, 307));
			jScrollPaneReplace.setFont(new Font("Courier New", Font.PLAIN, 12));
			jScrollPaneReplace.setViewportView(getJTableReplace());
		}
		return jScrollPaneReplace;
	}

}  //  @jve:decl-index=0:visual-constraint="10,10"
